package com.ghy.springbootsentinel;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphO;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: 卢佳新
 * @version: v1.0
 * @description: com.ghy.springbootsentinel
 * @date:2022/1/3 9:46
 * @Motto 不积跬步，无以至千里；不积小流，无以成江海。
 */
//单机限流
public class SentinelDemo {
    public static void main(String[] arg) {
        initFlowRule(); //初始化限流规则
        while(true){
            //ResourceName表示资源,控制访问流量的点
            try(Entry entry= SphU.entry("helloWorld")){
                System.out.println("hello world");
            }catch (BlockException e){
                System.out.println("被拒绝");
            }
//            if (SphO.entry("helloWorld")) {
//                System.out.println("Hello World");
//                SphO.exit();
//            }
        }
    }
    private static void initFlowRule(){
        List<FlowRule> rules=new ArrayList<> ();
        FlowRule flowRule=new FlowRule();
        flowRule.setResource("helloWorld"); //针对那个资源设置规则
        flowRule.setGrade( RuleConstant.FLOW_GRADE_QPS);//QPS或者并发数
        flowRule.setCount(5); //QPS=5
        flowRule.setControlBehavior ( RuleConstant.CONTROL_BEHAVIOR_DEFAULT );//直接拒绝
        rules.add(flowRule);
        FlowRuleManager.loadRules(rules);
    }
}
